#!/usr/bin/env python

import sys
from liwe.module import LiweModule

class Agenda ( LiweModule ):
	def __init__ ( self, liwe ):
		super ( Agenda, self ).__init__ ( liwe, "agenda" )

		self.dbm = self.liwe.dbm

	#=================================================
	# PUBLIC
	#=================================================

	def get_calendar ( self, id_cal = 0, cal_name = '', module= '', uid = 0, gid = 0 ):

		conds = []
		tables = [ 'agenda_profile AS r' ]
		fields = [ 'r.id_cal', 'r.cal_name', ]

		if id_cal:
			conds.append ( 'r.id_cal = %s' % id_cal ) 
			
		if cal_name:
			conds.append ( "r.cal_name = '%s'" % cal_name ) 

		if module:
			conds.append ( "r.module = '%s'" % module ) 

		#relation with agenda_rights table
		self._check_perms ( tables, fields, conds )

		tot_rows = 0
		tot_rows = self.dbm.count ( tables, fields, conds = ' AND '.join ( conds ) )
		res = self.dbm.all_rows ( tables, fields, conds = ' AND '.join ( conds ), debug = self.debug () )
		if not res:
			res = []
		return { 'rows' : res, 'tot_rows' : tot_rows } 

	def get_event ( self, id_cal = 0, uid = 0 , gid = 0, id_evt = 0, date_start = 0, date_end = 0 ): 

		both_date = 0
		conds = []
		tables = [ 'agenda_event AS a', 'agenda_rel AS r' ]
		fields = [ 'a.id_evt', 'a.id_descr', 'a.title', 'a.visible', 'a.uid', 'a.created', 'a.date_start', 'a.date_end', 'a.permalink' ]
		extras = "GROUP BY a.id_evt ORDER BY a.date_start ASC"

		conds.append ( 'a.id_evt = r.id_evt' )

		if id_cal:
			conds.append ( 'r.id_cal = %s' % id_cal )

		#relation with agenda_rights table
		self._check_perms ( tables, fields, conds )

		if date_start:
			#conds.append ( "a.date_start >= '%s'" % date_start )
			if date_end:
				conds.append ( "a.date_start BETWEEN CAST( '%s' AS DATETIME ) AND CAST( '%s' AS DATETIME )" % ( date_start, date_end ) )
				conds.append ( "a.date_end BETWEEN CAST( '%s' AS DATETIME ) AND CAST( '%s' AS DATETIME )" % ( date_start, date_end ) )
				both_date = 1
			else:
				conds.append ( "a.date_start >= CAST( '%s'AS DATETIME )" % date_start )

		if date_end and not both_date:
			conds.append ( "a.date_end <= CAST( '%s' AS DATETIME )" % date_end )

		if id_evt:
			conds.append ( 'a.id_evt = %s' % id_evt )

		cur = self.dbm.select ( tables, fields, conds = ' AND '.join ( conds ), extras = extras, debug = self.debug () ) 		
		if not cur:
			return []
		res = []
		for r in cur:
			#sys.stderr.write ( "\n\nAGENDA get_event r = %s\n\n" % r )
			id_page = r.get ( 'id_descr', 0 )	
			if  id_page: 
				r [ 'descr' ] = self.liwe.invoke ( "page_manager.ajax.get", id_page ) [ 'page' ][ 'txt' ]
			res.append ( r )
		return res

	def _check_perms ( self, tables, fields, conds ):

		sess = self._get_sess_data ()

		uid = sess [ 'uid' ]
		gid = sess [ 'gid' ]
		user_conds = []

		tables.append ( 'agenda_rights AS u ' )
		fields.extend ( [ 'u.uid', 'u.gid', 'u.perm' ] )
		conds.append ( 'r.id_cal = u.id_cal' )
		#conds.append ( "u.perm = 'r'" ) # 'r' read permission

		#if admin no check needed
		if sess [ 'login' ] == 'root':
			return

		if uid:
			user_conds.append ( 'u.uid = %s OR u.uid = 0' % uid )
		if gid:
			user_conds.append ( 'u.gid = %s OR u.gid = 0' % gid )

		if user_conds:
			conds.append ( "( " + " OR ".join ( user_conds ) + " ) " )

	#=================================================
	# USER EDIT
	#=================================================

	def add_event ( self, id_evt = 0, id_cals = '', title = '', descr = '', visible = 0, uid = 0, created = 0, date_start = 0, date_end = 0, permalink = '', tags = '' ):

		id_descr = 0	
		# Inserisco i dati nel page manager
                id_descr = self.liwe.invoke ( "page_manager.admin.create", descr, id_descr, "agenda" ) [ 'id_page' ]

		if not created:
			created = "*NOW()"

                uid = self.liwe.pyhp.session.data.get ( "uid", 0 )

		dct = {
			'title' : title,
			'id_descr' : id_descr,
			'visible' : visible,
			'uid' : uid,
			'created' : created,
			'date_start' : date_start,
			'date_end' : date_end,
			'permalink' : permalink
			}
		
		#self.dbm.debug = sys.stderr.write
		if id_evt:
			self.dbm.update ( 'agenda_event', dct, 'id_evt = %s' % id_evt )

		if not id_evt:
			dct [ 'id_evt' ] = ''
			self.dbm.insert ( 'agenda_event', dct )
			id_evt = self.dbm.insert_id () 
		#self.dbm.debug = None
		# save tags
		"""
                self.liwe.invoke ( "tags.admin.del_all_tags", id_obj = id_evt, id_site = self.liwe.cfg.get ( 'SITE_ID', 0 ), module = "agenda" )
                self.liwe.invoke ( "tags.ajax.tag_object", id_obj = id_evt, id_site = self.liwe.cfg.get ( 'SITE_ID', 0 ), tags = tags, module = "agenda" )
		"""
                self.liwe.invoke ( "tags.admin.del_all_tags", id_obj = id_evt, id_site = self.site_id, module = "agenda" )
                self.liwe.invoke ( "tags.ajax.tag_object", id_obj = id_evt, id_site = self.site_id, tags = tags, module = "agenda" )

		self._update_rel ( id_cals = id_cals, id_evt = id_evt, action = 'update' )
		
		return id_evt

	def del_event ( self, id_evt = 0 ):
		
		if not id_evt:
			return

		sess = self._get_sess_data ()

		tables = [ 'agenda_rel AS r' ]
		conds = [ "r.id_evt = %s" % id_evt ]

		#only if write permission in frontend is implemented
		"""
		tables.append ( 'agenda_rights AS u' )
		conds.append ( "r.id_cal = u.id_cal" )
		conds.append ( "( u.uid = %s OR u.gid = %s ) AND u.perm = 'w'" % ( sess [ 'uid' ], sess [ 'gid' ] ) )
		"""
		data = self.dbm.all_rows ( tables, 'r.id_cal', conds = " AND ".join ( conds ), debug = self.debug () )
		
		if not data:
			#self.liwe.set_error ( '001', "Permessi insufficienti" )
			return

		self.dbm.delete ( 'agenda_event', 'id_evt = %s' % id_evt )

		id_cals = []
		[ id_cals.append ( str ( cal.get ( 'id_cal' ) ) ) for cal in data ]

		cals = '|'.join ( id_cals )

		self._update_rel ( id_cals = cals, id_evt = id_evt )

	def _update_rel ( self, id_cals = '', id_evt = 0, action = '' ):
		
		ids = id_cals.split ( '|' )
		#self.dbm.debug = sys.stderr.write
		for id_cal in ids:
			self.dbm.delete ( 'agenda_rel', 'id_cal = %s AND id_evt = %s' % ( id_cal, id_evt ) )
			if action:
				self.dbm.insert ( 'agenda_rel', { 'id_cal' : id_cal, 'id_evt' : id_evt } )
		#self.dbm.debug = None
	#=================================================
	# ADMIN
	#=================================================

	def add_calendar ( self, id_cal = 0, cal_name = '', module = 'agenda', uid = 0, gid = 0 ):
		
		if not cal_name:
			return
		dct = {
			'uid' : uid,
			'gid' : gid,
			'module' : module
			}
		if id_cal:
			self.dbm.update ( 'agenda_profile', { 'cal_name' : cal_name }, 'id_cal = %s' % id_cal )
			self.dbm.update ( 'agenda_rights', dct, 'id_cal = %s' % id_cal )

		if not id_cal:
			self.dbm.insert ( 'agenda_profile',  { 'id_cal' : '', 'cal_name' : cal_name, 'module' : module } )
			id_cal = self.dbm.insert_id ()
			dct [ 'id_cal' ] = id_cal 
			self.dbm.insert ( 'agenda_rights', dct )

		return id_cal

	def del_calendar ( self, id_cal = 0 ):

		if not id_cal:
			return
		self.dbm.delete ( 'agenda_profile', 'id_cal = %s' % id_cal )
		self.dbm.delete ( 'agenda_rights', 'id_cal = %s' % id_cal )
		
		res = self.get_event ( id_cal = id_cal )
		if not res:
			res = []

		self.dbm.delete ( 'agenda_rel', 'id_cal = %s' % id_cal )
		
		for row in res:
			self.dbm.delete ( 'agenda_event', 'id_evt = %s' % row [ 'id_evt' ] )
		
	def _get_sess_data ( self ):
		sess = {
				'uid' 	: self.liwe.pyhp.session.data.get ( 'uid', 0 ),
				'gid' 	: self.liwe.pyhp.session.data.get ( 'gid', 0 ),
				'login' : self.liwe.pyhp.session.data.get ( 'login' ),
				'root' 	: self.liwe.pyhp.session.data.get ( 'root', 0 )
			}
		return sess
